﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WP.Modules;
using WP.DB;
using WP.Controls;
using WP.Commons;
using System.Collections;

namespace WP.IM.Form
{
    public partial class frmImCategoryWKRatingMtn : BaseMtn 
    {
        public frmImCategoryWKRatingMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }

        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select TypeId,TypeName from rmMaterialFirstType order by TypeId";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["TypeId"]) + "-" + CvtFunc.ToString(drType["TypeName"]));
                this.tvTree.Nodes.Add(tvNode);
                int intRow = 0;
                strSQL = "select MaterialTypeID,MaterialType from rmMaterialType where MaterialTypeID like '" + CvtFunc.ToString(drType["TypeID"]) + "%'";
                DataTable dtDtl = dbcon.GetDataTable(strSQL);
                foreach (DataRow drDtl in dtDtl.Rows)
                {
                    tvNode.Nodes.Add(CvtFunc.ToString(drDtl["MaterialTypeID"]) + "-" + CvtFunc.ToString(drDtl["MaterialType"]));
                }
            }
            dbcon.CloseCon();
        }

        private void frmImCategoryWKRatingMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!this.UpdateData()) return;
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            base.ExportToExcel(dgList);
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText = "定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText = "定位到下一页";
                this.btnPrev.ToolTipText = "定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText = "定位到末记录";
                this.btnTop.ToolTipText = "定位到首记录";
                this.btnNext.ToolTipText = "定位到下一条记录";
                this.btnPrev.ToolTipText = "定位到上一条记录";
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null)
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work
           
        }
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);            
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;
            if (con.Name == txtItemName.Name)
            {
                txtItemName.Text = DataFunctions.GetFieldValue("iminvmaster", "itemname", "fitemID='" + txtFItemID.Text + "'");
            }
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }

        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);

              
            }
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

       

        #region ***Form Functions

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();


            IM.BusinessRule.ImCategoryWKRatingBRL mBRL = new WP.IM.BusinessRule.ImCategoryWKRatingBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;

        }
        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            if (strLookUpControlName == ubtWKName.Name)
            {
                return strSql = "select RecID, WorkingProcedureID as 工序编码,WorkingProcedureName as 工序名称 from rmWorkingProcedure  order by WorkingProcedureID";
            }
            else 
                return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
            Control con = sender as Control;
            if (con.Name == ubtItemNo.Name)
            {

                string strSQL = base.GetLookUpSQL("ImInvMaster", ubtItemNo.Name);
                frmLookUpItem frmlookup = new frmLookUpItem(strSQL, "物料选择", con.Text, "FItemID");
                frmlookup.ShowDialog();
                if (frmlookup.HaveReturnValue)
                {
                    txtFItemID.Text = frmlookup.GetReturnValue("FItemID");
                    txtItemNo.Text = frmlookup.GetReturnValue("ItemNo");
                    txtItemName.Text = frmlookup.GetReturnValue("ItemName");
                    txtSupName.Text = frmlookup.GetReturnValue("SupName");
                    txtSupNo.Text = frmlookup.GetReturnValue("SupNo");
                }
                frmlookup.Close();
            }
            else if (con.Name == ubtWKName.Name)
            {
                string strSQL = base.GetLookUpSQL("rmWorkingProcedure");
                frmLookUpWK frmlookup = new frmLookUpWK(strSQL, "工序选择", con.Text, "WorkingProcedureID");
                frmlookup.ShowDialog();
                if (frmlookup.HaveReturnValue)
                {
                    txtWKProductID.Text = frmlookup.GetReturnValue("WorkingProcedureID");
                    txtWKName.Text = frmlookup.GetReturnValue("WorkingProcedureName");
                }
                frmlookup.Close();
            }
            else
            {
                base.ubtLookUp_Click(sender, e);
            }
        }
        public override void SetButtonStatus()
        {
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = false ;
                    this.btnCancel.Enabled = true;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = ( true  && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true  && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = true ;
                    this.btnCancel.Enabled = true;
                    this.btn_CopyTo.Enabled = true;
                    
                    break;
                case FormStatus.Loading:
                    break;

            }

            this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;

            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;

            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;

            
            
        }
        public override void SetOtherStatus()
        {
          
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtItemNo.Focus();
                    break;
                case FormStatus.Delete:
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    break;
                case FormStatus.Loading:
                    break;
            }

            
        }
        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("FItemID", "ImInvMaster", "FItemID", "ubtItemNo");
            SetFieldLookUpInfo("ItemNo", "ImInvMaster", "ItemNo", "ubtItemNo");
            SetFieldLookUpInfo("ItemName", "ImInvMaster", "ItemName", "ubtItemNo");
            SetFieldLookUpInfo("SupName", "ImInvMaster", "SupName", "ubtItemNo");
            SetFieldLookUpInfo("SupNo", "ImInvMaster", "SupNo", "ubtItemNo");

            //SetFieldLookUpInfo("CategoryName", "rmCategoryWK", "CategoryName", "ubtWKName");
            //SetFieldLookUpInfo("CategoryID", "rmCategoryWK", "CategoryID", "ubtWKName");

            SetFieldLookUpInfo("WKName", "rmWorkingProcedure", "WorkingProcedureName", "ubtWKName");
            SetFieldLookUpInfo("WKProductID", "rmWorkingProcedure", "WorkingProcedureID", "ubtWKName");
        }

        #endregion Form Functions***

        private void frmImCategoryWKRatingMtn_Load(object sender, EventArgs e)
        {
             this.TableName = "ImCategoryWKRating";
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;

            FillLookUpInfo();
            FillTree(); 
        }

        private void btn_CopyTo_Click(object sender, EventArgs e)
        {
            string strNewCategoryID="";
            string strNewCategoryName = "";
            string strNewWKID="";
            string strNewWKName = "";
            string strFItemID =txtFItemID.Text ;
            frmImCategoryWKRatingCopy frmShowCopy = new frmImCategoryWKRatingCopy();
            if (frmShowCopy.ShowCopyItem(ref strNewCategoryID,ref strNewCategoryName , ref strNewWKID,ref strNewWKName, strFItemID ))
            {
                DBAccess dbcon = new DBAccess(false, false);
                string strSQL = "insert into ImCategoryWKRating ( CategoryID,CategoryName,WKProductID,WKName,FItemID,ItemNo,ItemName,SupNo,SupName,QtyUnit,Remark)";
                strSQL += " select '"+ strNewCategoryID +"','{2}','"+ strNewWKID +"','{3}','"+ txtFItemID.Text  +"',ItemNo,ItemName,SupNo,SupName,QtyUnit,Remark from ImCategoryWKRating where CategoryID='{0}' and WKProductID='{1}' and FItemID='{4}'";
                strSQL = string.Format(strSQL, txtCategoryID.Text 
                                                , txtWKProductID.Text  
                                                , strNewCategoryName
                                                , strNewWKName
                                                , txtFItemID.Text );
                dbcon.ExecuteSql(strSQL);
                
                MsgBoxEx.Show("复制完成。", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                string strRecID = dbcon.GetValue ("select recid from  ImCategoryWKRating where FItemID='"+ txtFItemID.Text + "' and  CategoryID='"+ strNewCategoryID +"' and WKProductID='"+ strNewWKID +"'");
                this.RecID = CvtFunc.ToLong (strRecID);
                dbcon.CloseCon();
            }
            
        }

        private void dgList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0) //最后一层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = " ItemNo like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
            else  //最上层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = " ItemNo like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
        }
        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " where " + strWhereCondition;
                strSql += strOrderBy;
            }
            //string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            //mstrWhereCondition = strWhere;
            this.dgList.Sql = strSql;
        }
    }
}
